//處理頁面載入
$(function() {
	//初始化選單
	menuProcessor.init();
	
	pageFlow.init();
	
	var logoutFun = function() {
		$.ajax({
			url:"Welcome_ajaxLogout.action",
			success: function(response) {
				window.opener=null; 
				window.open("","_self"); 
				window.close(); 
			}
		})
	};
	$("#functionF10").click(logoutFun);
	
	$(document).keydown(function(event) {
		switch (event.keyCode) {
		case 112://F1
			break;
		case 113://F2
			break;
		case 114://F3
			break;
		case 115://F4
			break;
		case 116://F5
			break;
		case 117://F6
			break;
		case 118://F7
			break;
		case 119://F8
			break;
		case 120://F9
			break;
		case 121://F10
			logoutFun();
			break;
		case 122://F11
			if ($("#yimForm #DOCNM").val()) {
				$("#yimForm").submit();
			}
			break;
		case 123://F12
			break;
		}
	})
	
	window.onerror = pageFlow.handelException;
});

var PageFlow = {
	init: function() {
		$.ajaxSettings.traditional = true;
		
		$("#container button").button();
		
		$("table").beautyTable();
	},
	showScreenCode: function(screenCodeObj) {
		var screenCode = $(screenCodeObj).html();
		var imageLink = "/tasshare/fdc/uipng/"+screenCode.substring(0,3).toLowerCase()+"/ui/"+screenCode+".png"
		window.open(imageLink,screenCode);
	},
	showTsdl: function(tsdlCodeObj,mySvcRid) {
		var tsdlCode = $(tsdlCodeObj).html();
		var imageLink = "/tasweb/Service_viewSchema.action?svcRid="+mySvcRid+"#"+tsdlCode;
		window.open(imageLink,'tsdl');
	},
	//顯示對話框
	showDialog: function(title,msg,confirmCb) {
		$("#dialog").html(msg);
		$("#dialog").dialog({'modal':true,'title':title,'width':300,'height':'auto','buttons':this.getDialogBtn(confirmCb)});
	},
	//顯示大型對話框
	showLargeDialog: function(title,msg,confirmCb) {
		$("#dialog").html(msg);
		$("#dialog").dialog({'modal':true,'title':title,'width':800,'height':500,'buttons':this.getDialogBtn(confirmCb)});
	},
	//取得對話框按鈕
	getDialogBtn: function(confirmCb) {
		if (confirmCb) {
			return [{text: "確定",click: function() {confirmCb();$(this).dialog("close");}},{text: "取消",click: function() {$(this).dialog("close");}}]; 
		} else {
			return [{text: "確定",click: function() {$(this).dialog("close");}}];
		}
	},
	//重導頁面
	redirect: function(action, datas) {
		if (datas) {
			$.each(datas, function(key, value) {
				$("#redirectForm").append($("<input type='hidden'>").attr({
					"name" : key,
					"value" : value
			}));
		});
		}
		$("#redirectForm").attr({'action':action,target:'_self'});
		$("#redirectForm").submit();
	},
	
	//送出頁面,targetName與methodName為選項
	submitForm: function(formId,actionUrl,targetName,methodName) {
		if (!targetName) {
			targetName = "_self";
		}
		if (methodName!="get") {
			methodName = "post";
		}
		
		var hasClass = function(ele, cls) {
            return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
		}
		
		
		
		$('#'+formId+" select").each(function(index, inputObj) {
			 if (inputObj.type == 'select-multiple' || hasClass(inputObj, 'chosenMultiUnit')) {
				 if (!hasClass(inputObj, 'formMulipleSelectField')) {
					 for (var i=0;i<inputObj.options.length;i++) {
						 inputObj.options[i].selected = true;
					 }
			 	 }
			 }
		});
		
		$('#'+formId+" input").each(function(index, inputObj) {
			if (inputObj["realValue"]) {
				inputObj["tmpValue"]  = inputObj.value;
				inputObj.value = inputObj["realValue"];
			}
		});
		
		$('#'+formId).attr({
                        target : targetName,
                        method : methodName,
                        action : actionUrl
                }).submit();
		
		$('#'+formId+" input").each(function(index, inputObj) {
			if (inputObj["realValue"]) {
				inputObj.value = inputObj["tmpValue"];
			}
		});
	},
	
	selectAllMulti: function(formId) {
		$("#" + formId + " select").each(function(index, inputObj) {
			if (inputObj.type == "select-multiple") {
				$(inputObj).children("option").each(function(ind, opt) {
					$(opt).attr("selected", "true");
				});
			}
		});
	},
	
	selectAll : function(selAllObj) {
		var selected = selAllObj.checked;
		checkboxList = $(selAllObj).parent().parent().find(":checkbox");
		if (selected) {
			checkboxList.attr("checked","checked");
		} else {
			checkboxList.removeAttr("checked");
		}
		checkboxList.change();
	},
	
	exportFormByKey: function(keyName,keyValue,actionUrl) {
		var hiddenObj = $("<input type='hidden' name='"+keyName+"' value='"+keyValue+"'/>");
		$("#redirectForm").find("input:hidden").remove();
		$("#redirectForm").append(hiddenObj);
		$("#redirectForm").attr({'action':actionUrl,target:'_blank'});
		$("#redirectForm").submit();
	},
	showMessage: function(msg) {
		if (msg.trim().length==0) {
			this.hideMessage();
			return;
		}
		$("#messageBar div font").html(msg);
		$("#messageBar").fadeOut(200,function(){$("#messageBar").fadeIn(500);});
	},

	hideMessage: function() {
		$("#messageBar").fadeOut(200);
	},
	handelException: function(msg,url,num) {
        logger.error(msg, url, num);
        var stackTrace = printStackTrace();
        var print = false;
        var printString = msg + " : " + url + ", line:"+ num+ "\r\n";
        for (i=0;i<stackTrace.length;i++) {
            if (stackTrace[i].indexOf("handelException")!=-1) {
               stackTrace[i] = stackTrace[i].replace("Object.handelException", "");
               print = true;
            }
            if (print) {
               printString += stackTrace[i] + "\r\n";
            }
       }
       pageFlow.showLargeDialog("javascript錯誤", printString);
       $("#ajaxMask").hide();
       $("#ajaxLoader").hide();  
       return true;
    },
	//動態載入js
	loadJs: function(url,callBack) {
		if (!url) {
			return;
		}
		var done = false;
		var newJs = document.createElement('script');
		newJs.type = 'text/javascript';
		newJs.src= url;
		newJs.onload = newJs.onreadystatechange = function() {
			if ( !done && (!this.readyState ||
		            this.readyState === "loaded" || this.readyState === "complete") ) {
		        done = true;
		        // Handle memory leak in IE
		        newJs.onload = newJs.onreadystatechange = null;
				if (callBack) {
					callBack();
				}
		    }
		}
		$("head").get(0).appendChild(newJs);
	},
	
	//動態載入多個js
	loadMultiJs: function(url1,url2,url3,url4,url5,url6) {
		var loadJsFun = this.loadJs;
		loadJsFun(url1, function() {
			loadJsFun(url2,function() {
				loadJsFun(url3,function() {
					loadJsFun(url4,function() {
						loadJsFun(url5,function() {
							loadJsFun(url6);
						});
					});
				});
			});
		});
	},
	
	updateBitmap: function(id, bitOrder, checkBox) {
		var bmJsonObj = $(checkBox.parentNode).children("#" + id);
		if (bmJsonObj.size() <= 0) {
			bmJsonObj = $(checkBox.parentNode.parentNode).children("#" + id);
		}
		var bitmapJson = bmJsonObj.val();
		logger.log("bitmapJson: " + bitmapJson);
		var bitmap = $.parseJSON(bitmapJson);
		logger.log("bimap: " + bitmap.enumClassName + ", " + bitmap.value);
		var bmValue = parseInt(bitmap.value, 10);
		if (checkBox.checked) {
			bmValue = bmValue | (1 << bitOrder);
		} else {
			bmValue = bmValue & ( 2147483647 ^ (1 << bitOrder));
		}
		logger.log("bmValue: " + bmValue);
		bitmap.value = bmValue;
		bitmapJson = $.toJSON(bitmap);
		logger.log("bitmapJson: " + bitmapJson);
		bmJsonObj.val(bitmapJson);
	},
	
	resetForm: function(form) {
		$(form).find("select.chosen option").remove();
		$(form).find("div.fileinput-wrapper span.fileinput-input").html("");
		$(form).find("div.fileupload button.delete").click();
		$(form).find("select.chosenMultiUnit option").remove();
		
		$(form).find("a.autoComplete input").each(function(index,obj) {
			obj['realValue'] = null;
		});
		$(form).find("input.realValue").each(function(index,obj){
			obj.value = "";
			obj["realValue"] = null;
		});
		//$(form).find("input[type=text]").not(".hidden").val("");
		$(form).find("input[type=text]").not(".hidden").each(function(index,obj){
			var iobj = $(obj);
			iobj.val("");
			if (iobj.attr("onchange")) {
				eval(iobj.attr("onchange"));
			}
		});
		$(form).find("input[type=checkbox]").attr("checked",false);
		$(form).find("input.fileinput-file").val("");
		$(form).find("textarea").val("");
		$(form).find("select").each(function(index,selObj) {
			$(selObj).children("option").attr("selected",false);
			$(selObj).children("option:first").attr("selected",true);
		});
		$(form).find("input[type=radio]").attr("checked",false);
		$(form).find("input.bitmap").each(function(index,element){
			var jsonObj = $.parseJSON(element.value);
			jsonObj.value = 0;
			element.value = $.toJSON(jsonObj);
		});
		var validator = $(form).validate();
		validator.resetForm( );
	}
}

var pageFlow = $.extend({},PageFlow);

String.prototype.trim = function(){
	return (this.replace(/^[\s\xA0]+/,  "").replace(/[\s\xA0]+$/, ""));
}

String.prototype.startsWith = function(str) {
	return (this.match("^"+str)==str)
}
String.prototype.endsWith = function(str) {
	return (this.match(str+"$")==str)
}
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.unCapitalize = function() {
    return this.charAt(0).toLowerCase() + this.slice(1);
}

String.prototype.zf = function(l) {
	return '0'.string(l - this.length) + this;
}
String.prototype.string = function(l) {
	var s = '', i = 0;
	while (i++ < l) {
		s += this;
	}
	return s;
}
Number.prototype.zf = function(l) {
	return this.toString().zf(l);
}

Date.prototype.format = function(f)
{
    if (!this.valueOf())
        return ' ';

    var d = this;

    return f.replace(/(yyyy|mm|dd|hh|nn|ss)/gi,
        function($1)
        {
            switch ($1.toLowerCase())
            {
            case 'yyyy': return d.getFullYear();
            case 'mm':   return (d.getMonth() + 1).zf(2);
            case 'dd':   return d.getDate().zf(2);
            }
        }
    );
}